package edu.hzit.data.interceptors;


import edu.hzit.data.utils.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        System.out.println(token);
        if (token != null && !"".equals(token)) {
            //验证token
           try {
               String rightToken = new TokenUtil().createToken(token.split("\\.")[0]);
               System.out.println("aaa"+rightToken);
               boolean i=rightToken.equals(token);
               System.out.println("aaaa"+i);
               if (rightToken.equals(token)) {
                   return true;
               } else {
                   //抛出自定义异常，通过全局异常处理返回给前端一个VO（包含“请先登录”提示信息）
                   throw new UnTokenException("非法token，请认证");
               }

           }catch (Exception e){
               e.printStackTrace();
           }



        } else {
            throw new UnTokenException("请求参数不正确（缺少token）");
        }return false;
    }
}
